﻿using System.Collections.Generic;
using System.Linq;

namespace TimeProject.WebSite.ViewModels
{
    public partial class MyOrganizationsViewModel : ViewModelBase
    {
        /// <summary>
        /// All organizations where the current user is member of.
        /// </summary>
        public List<MyOrganizationViewModel> Organizations { get; set; }

        public bool IsCreateNewOrganizationAllowed { get; set; }

        public bool IsJoinOrganizationAllowed { get; set; }

        protected override void OnInitialize()
        {
            base.OnInitialize();
            Organizations = new List<MyOrganizationViewModel>();
            IsCreateNewOrganizationAllowed = true;
            IsJoinOrganizationAllowed = true;
        }

        public virtual void SetAsSelected(MyOrganizationViewModel organization)
        {
            foreach (var item in Organizations)
            {
                if (item == organization)
                {
                    item.IsSelected = true;
                }
                else
                {
                    item.IsSelected = false;
                }
            }            
        }

        public virtual void CreateNewOrganization()
        {
            MyOrganizationViewModel newOrganization = new MyOrganizationViewModel
            {
                PublicId = "Not available",
                IsNew = true,
                IsFullyLoaded = true,
                IsManageAllowed = true,
                IsDeleteAllowed = true,
                IsRemoveMembershipAllowed = true
            };

            Organizations.Add(newOrganization);
            SetAsSelected(newOrganization);

            IsCreateNewOrganizationAllowed = false;
            IsJoinOrganizationAllowed = false;
            isDirty = true;
        }

        public virtual void DeleteOrganization(MyOrganizationViewModel organization)
        {
            if (organization.IsNew)
            {
                Organizations.Remove(organization);
            }
            else
            {
                organization.IsDeleted = true;
            }

            if (Organizations.Any(x => x.IsNew))
            {
                IsCreateNewOrganizationAllowed = false;
                IsJoinOrganizationAllowed = false;
            }
            else
            {
                IsCreateNewOrganizationAllowed = true;
                IsJoinOrganizationAllowed = true;
            }

            isDirty = true;
        }

    }
}
